--
-- @Author:      name
-- @DateTime:    2018-03-30 23:05:48
-- @Description: 消息的处理

local skynet = require "skynet"
local log = require "Logger"
-- local config = require "configquery"
local cluster = require "skynet.cluster"




local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch, node_message)
	
	
	self.proto_file = skynet.getenv("proto_config") --proto文件路径	
    self.server_id = tonumber(skynet.getenv("svr_id"))
    self.server_type = skynet.getenv("server_type") or ""
    self.server_name = skynet.getenv("server_name") or ""
    self.cluster_addr = skynet.getenv("cluster_addr")
    self.cluster_name = skynet.getenv("cluster_name")
    self.zone_server_id = tonumber(skynet.getenv("zone_cluster_id")) or 0


	self.message_dispatch = message_dispatch
	self.node_message = node_message
	self.server_manager = nil



	self:register()
end

--注册本服务里的消息
function MessageHandler:register()

	self.message_dispatch:registerSelf('start', handler(self,self.start))
	self.message_dispatch:registerSelf('server_register_req', handler(self,self.serverRegisterReq))
    self.message_dispatch:registerSelf('client_req', handler(self,self.clientReq))

    self.message_dispatch:registerSelf('send_to_server', handler(self,self.sendToServer))

    self.message_dispatch:registerSelf('send_to_user', handler(self,self.sendToUser))
    self.message_dispatch:registerSelf('broadcast_to_user', handler(self,self.broadcastToUser))
    self.message_dispatch:registerSelf('assign_sever_nt', handler(self,self.assignServerNt))
    
end

--启动
function MessageHandler:start()

    self.server_manager = global.server_manager
	--skynet控制台
	-- skynet.newservice("debug_console", svr_config.debug_port)

    --
end

--收到别的服务器注册
function MessageHandler:serverRegisterReq(msg_data)
    print("_________收到服务器注册______",msg_data)
    local msg_body = msg_data
    local server = self.server_manager:getServer(msg_body.server_id)
    if server then
        --发送注册结果
        local result = {
            error_code = 0,
            error_msg = "服务器注册失败，有相同服务器标识的服务器已经注册了！"
        }
        self.node_message:sendNodeProxy(msg_body.cluster_id, "server_register_res", result)
        return 
    else
        server = {
            server_id = msg_body.server_id,
            server_type = msg_body.server_type,
            server_name = msg_body.server_name,
            cluster_addr = msg_body.cluster_addr,
            cluster_name = msg_body.cluster_name,          
        }
        self.server_manager:addServer(server)
    end

    --把注册的服务器添加到自己的集群列表中
    if not server.cluster_name then 
        return 
    end

    -- 重新加载集群配置
    local cluster_name = server.cluster_name
    local cluster_addr = server.cluster_addr 
    local cluster_config = {
        [cluster_name] = cluster_addr,
    }
    cluster.reload(cluster_config)

    --发送注册结果
    local result = {
        error_code = 0,
        error_msg = "服务器注册成功"..msg_body.server_id,
    }
	self.node_message:sendNodeProxy(cluster_name, "server_register_res", result)

end

--客户端的请求， 需要转发
function MessageHandler:clientReq(user_id, main_id, data)
    print("________nodeserver__clientReq___",user_id,main_id, data)
    local des_server
    if main_id == 2001 then --转发到hallserver
        des_server = self.server_manager:getHallServer(user_id)
    elseif main_id==3001 or main_id>10000 then --转发到gameserver 
        des_server = self.server_manager:getGameServer(user_id)
    end    
    if not des_server then 
        log.error("___消息转发失败__没找到对应的服务器___",user_id, main_id, data, self.server_manager:getServerList())
        return 
    end
    -- print("____self.server_manager__",self.server_manager.user_list)
    local res = self.node_message:callNodeProxy(des_server, 'dispatch', data.callback, data.message_body)
    return res
end

function MessageHandler:sendToServer(data)
    print("________nodeserver__sendToServer___", data)
    local des_server, desk_id
    local server_type = data.server_type
    local user_id = data.user_id
    if server_type=="hallserver" then --转发到gameserver 
        des_server = self.server_manager:getHallServer(user_id)        
    elseif server_type=="gameserver" then --转发到gameserver 
        des_server, desk_id = self.server_manager:getGameServer(user_id)
        if not data.message_body.desk_id then 
            data.message_body.desk_id = desk_id
        end
    end    
    if not des_server then 
        log.error("__sendToServer_消息转发失败__没找到对应的服务器___",user_id, main_id, data, des_server)
        return 
    end
    -- print("____self.server_manager__",self.server_manager.user_list)
    local res = self.node_message:sendNodeProxy(des_server, 'dispatch', data.message_name, data.message_body)
    return res
end

--给指定玩家发送消息
function MessageHandler:sendToUser(user_id, cmd, data)
    print("________sendToUser___",user_id,cmd, data)
    local gateserver = self.server_manager:getGateServer(user_id)
    if not gateserver then 
        print("___没有找到__gateserver____",user_id)
        return
    end
    self.node_message:sendUser(gateserver,user_id, cmd, data)
end

--给多个玩家发消息
function MessageHandler:broadcastToUser(user_list, cmd, data)
    -- print("________broadcastToUser___",user_list,cmd, data)
    --要分出在同一个网关的玩家一次性发出
    local gate_users = {}
    for _,user_id in pairs(user_list) do 
        local gateserver = self.server_manager:getGateServer(user_id)
        if not gateserver then 
            print("__broadcastToUser_没有找到__gateserver____",user_id)            
        else
            if not gate_users[gateserver] then 
                gate_users[gateserver] = {}
            end
            table.insert(gate_users[gateserver], user_id)            
        end        
    end
    for gateserver, users in pairs(gate_users) do         
        self.node_message:sendUsers(gateserver, users, cmd, data)
    end
end

--用户身上服务器信息发生改变
function MessageHandler:assignServerNt(msg_data)
    print("________assignServerNt___",msg_data)
    self.server_manager:addUser(msg_data)
end


return MessageHandler